package com.ssy.lingxi.product.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.product.BrandStatusEnum;
import com.ssy.lingxi.common.constant.product.CheckTypeEnum;
import com.ssy.lingxi.common.constant.product.CommodityStatusEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.model.vo.SelectVO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.platform.manage.api.feign.inner.ShopRuleActivityFeign;
import com.ssy.lingxi.platform.manage.api.feign.inner.SiteControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.shop.ShopMemberInfoDTO;
import com.ssy.lingxi.platform.manage.api.model.dto.site.SiteIdDTO;
import com.ssy.lingxi.product.api.model.request.BrandRequest;
import com.ssy.lingxi.product.api.model.request.CheckRequest;
import com.ssy.lingxi.product.api.model.response.BrandResponse;
import com.ssy.lingxi.product.api.model.response.SimpleBrandResponse;
import com.ssy.lingxi.product.common.enums.CheckStatusEnum;
import com.ssy.lingxi.product.common.enums.OperationEnum;
import com.ssy.lingxi.product.entity.Brand;
import com.ssy.lingxi.product.entity.BrandCheckRecord;
import com.ssy.lingxi.product.entity.commodity.Commodity;
import com.ssy.lingxi.product.repository.BrandCheckRecordRepository;
import com.ssy.lingxi.product.repository.BrandRepository;
import com.ssy.lingxi.product.repository.GoodsRepository;
import com.ssy.lingxi.product.repository.commodity.CommodityRepository;
import com.ssy.lingxi.product.service.IBrandService;
import com.ssy.lingxi.product.service.ICommodityService;
import com.ssy.lingxi.product.service.customer.ICustomerCategoryAttributeService;
import com.ssy.lingxi.product.service.es.ISyncEsCommodityService;
import com.ssy.lingxi.product.service.platform.ICategoryAttributeService;
import com.ssy.lingxi.report.api.enums.CommodityOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * 品牌实现类
 *
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class BrandServiceImpl implements IBrandService {

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private CommodityRepository commodityRepository;

    @Resource
    private ICommodityService commodityService;

    @Autowired
    private BrandCheckRecordRepository brandCheckRecordRepository;

    @Autowired
    private GoodsRepository goodsRepository;

    @Resource
    private ReportControllerFeign reportControllerFeign;

    @Resource
    private ISyncEsCommodityService syncEsCommodityService;

    @Resource
    private SystemMessageControllerFeign systemMessageControllerFeign;

    @Resource
    private IRedisStringUtils redisStringUtils;

    @Resource
    private ShopRuleActivityFeign shopRuleActivityFeign;
    @Resource
    private SiteControllerFeign siteControllerFeign;

    @Resource
    private ICustomerCategoryAttributeService customerCategoryAttributeService;

    @Resource
    private ICategoryAttributeService categoryAttributeService;

    /**
     * 查询品牌列表 -- 商品能力
     *
     * @param pageVO
     * @param name
     * @param status
     * @return Page<Attribute>
     */
    @Override
    public Page<Brand> getBrandList(UserLoginCacheDTO sysUser, PageVO pageVO, String name, Integer status) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        if (status != null && status > 0) {
            return brandRepository.findByMemberIdAndMemberRoleIdAndNameContainingAndStatusOrderByApplyTimeDesc(memberId, memberRoleId, name, status, page);
        } else {
            return brandRepository.findByMemberIdAndMemberRoleIdAndNameContainingOrderByApplyTimeDesc(memberId, memberRoleId, name, page);
        }
    }

    /**
     * 查询待审核品牌列表--商品能力
     *
     * @param pageVO 分页实体
     * @param status 品牌状态(0-代表查全部,2-待审核,3-审核不通过,4-审核通过)
     * @return
     */
    @Override
    public Page<Brand> getUnCheckBrandList(UserLoginCacheDTO sysUser, PageVO pageVO, String name, String memberName, Integer status) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return brandRepository.findByMemberIdAndMemberRoleIdAndStatusAndTypeAndNameContainingAndMemberNameContainingOrderByApplyTimeDesc(sysUser.getMemberId(), sysUser.getMemberRoleId(), status, CheckTypeEnum.MEMBER_CHECK.getCode(), name, memberName, page);
    }

    /**
     * 查询品牌
     *
     * @param id
     * @return Brand
     */
    @Override
    public Brand getBrand(UserLoginCacheDTO sysUser, Long id) {
        return brandRepository.findById(id).orElse(null);
    }

    /**
     * 添加/修改品牌
     *
     * @param brandRequest
     * @return
     */
    @Transactional
    @Override
    public Long saveOrUpdateBrand(UserLoginCacheDTO sysUser, BrandRequest brandRequest) {
        Brand brand = BeanUtil.copyProperties(brandRequest, Brand.class);

        Long resultBrandId;
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long id = brand.getId();
        String name = brand.getName();
        Boolean flag;
        Boolean enableMultiTenancy = true;
        Brand sourceBrand;
        List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
        //调用平台管理服务->判断当前会员是否有自营商城
        ShopMemberInfoDTO dto = new ShopMemberInfoDTO();
        dto.setMemberId(sysUser.getMemberId());
        dto.setMemberRoleId(sysUser.getMemberRoleId());
        Wrapper<Boolean> existShop = shopRuleActivityFeign.existShop(dto);
        Boolean result = existShop.getData();
        //调用平台管理服务->判断当前站点是否开启多租户模式
        SiteIdDTO idDTO = new SiteIdDTO();
        idDTO.setSiteId(brandRequest.getSiteId());
        Wrapper<Boolean> wrapper = siteControllerFeign.enableMultiTenancy(idDTO);
        //用户没自营商城且SaaS未开启多租户模式
        if (!result || !wrapper.getData()) {
            brand.setType(CheckTypeEnum.PLATFORM_CHECK.getCode());//平台审核
        }
        //判断是新增还是修改
        if (id != null && id > 0) {
            //验证数据库中是否存在该数据
            Brand current_brand = brandRepository.findById(id).orElse(null);
            if (current_brand != null) {
                //判断是否存在修改中的记录
                sourceBrand = current_brand.getSourceBrand();
                if (sourceBrand != null) {
                    Long sourceBrandId = sourceBrand.getId();
                    flag = brandRepository.existsBySourceBrandIdAndIdNot(sourceBrandId, id);
                } else {
                    flag = brandRepository.existsBySourceBrandId(id);
                }
                if (flag) {
                    throw new BusinessException(ResponseCode.PRODUCT_BRAND_EXIST_UPDATE);
                }
                //判断名称是否重复
                flag = brandRepository.existsByMemberIdAndMemberRoleIdAndNameAndIdNot(memberId, memberRoleId, name, id);
                if (flag) {
                    throw new BusinessException(ResponseCode.PRODUCT_BRAND_NAME_EXIST);
                }
                Integer current_status = current_brand.getStatus();

                //如果是审核通过的，新增一条品牌数据
                Integer new_status = CommodityStatusEnum.Not_Submitted.getCode();
                if (BrandStatusEnum.Pass.getCode().equals(current_status)) {
                    Brand newBrand = new Brand();
                    newBrand.setName(brand.getName());
                    newBrand.setLogoUrl(brand.getLogoUrl());
                    newBrand.setProveUrl(brand.getProveUrl());
                    newBrand.setStatus(new_status);
                    newBrand.setIsEnable(true);
                    newBrand.setSourceBrand(current_brand);
                    newBrand.setSourceBrandName(current_brand.getName());
                    newBrand.setMemberId(memberId);
                    newBrand.setMemberName(sysUser.getCompany());
                    newBrand.setMemberRoleId(memberRoleId);
                    newBrand.setMemberRoleName(sysUser.getMemberRoleName());
                    newBrand.setUserId(sysUser.getUserId());
                    newBrand.setUserName(sysUser.getUserName());
                    newBrand.setType(brand.getType());
                    //数据库持久化对象
                    brandRepository.saveAndFlush(newBrand);
                    resultBrandId = newBrand.getId();
                    try {
                        //品牌总数
                        OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                        operateNoticeVO.setMemberId(memberId);
                        operateNoticeVO.setRoleId(memberRoleId);
                        operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                        operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.BRAND_COUNT.getCode());
                        operateNoticeVO.setIncreaseCount(1L);
                        operateNoticeVOList.add(operateNoticeVO);
                        //待提交审核品牌
                        operateNoticeVO = new OperateNoticeVO();
                        operateNoticeVO.setMemberId(memberId);
                        operateNoticeVO.setRoleId(memberRoleId);
                        operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                        operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_VALIFY_COMMIT.getCode());
                        operateNoticeVO.setIncreaseCount(1L);
                        operateNoticeVOList.add(operateNoticeVO);
                        reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if (BrandStatusEnum.Not_Check.getCode().equals(current_status)) {
                        throw new BusinessException(ResponseCode.PRODUCT_BRAND_UNENABLE);
                    }
                    brand.setMemberId(memberId);
                    brand.setMemberName(sysUser.getCompany());
                    brand.setMemberRoleId(memberRoleId);
                    brand.setMemberRoleName(sysUser.getMemberRoleName());
                    brand.setUserId(sysUser.getUserId());
                    brand.setStatus(new_status);
                    brand.setApplyTime(current_brand.getApplyTime());
                    brand.setCheckTime(current_brand.getCheckTime());
                    brand.setIsEnable(current_brand.getIsEnable());
                    brand.setSourceBrand(current_brand.getSourceBrand());
                    if (current_brand.getSourceBrand() != null) {
                        brand.setSourceBrandName(current_brand.getSourceBrand().getName());
                    }
                    brand.setUserName(sysUser.getUserName());
                    //数据库持久化对象
                    brandRepository.saveAndFlush(brand);
                    resultBrandId = brand.getId();
                }

                //品牌修改记录
                BrandCheckRecord brandCheckRecord = new BrandCheckRecord();
                brandCheckRecord.setMemberRoleId(sysUser.getMemberRoleId());
                brandCheckRecord.setMemberRoleName(sysUser.getMemberRoleName());
                brandCheckRecord.setOperation(OperationEnum.Update.getCode());
                brandCheckRecord.setStatus(new_status);
                brandCheckRecord.setCreateTime(System.currentTimeMillis());
                brandCheckRecord.setBrandId(id);
                brandCheckRecordRepository.saveAndFlush(brandCheckRecord);
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
            }
        } else {
            flag = brandRepository.existsByMemberIdAndMemberRoleIdAndName(memberId, memberRoleId, name);
            if (flag) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_NAME_EXIST);
            }
            brand.setIsEnable(true);
            brand.setStatus(CommodityStatusEnum.Not_Submitted.getCode());
            brand.setMemberId(memberId);
            brand.setMemberName(sysUser.getCompany());
            brand.setMemberRoleId(memberRoleId);
            brand.setMemberRoleName(sysUser.getMemberRoleName());
            brand.setUserId(sysUser.getUserId());
            brand.setUserName(sysUser.getUserName());
            //数据库持久化对象
            brandRepository.saveAndFlush(brand);
            resultBrandId = brand.getId();

            try {
                //品牌总数
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(memberId);
                operateNoticeVO.setRoleId(memberRoleId);
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.BRAND_COUNT.getCode());
                operateNoticeVO.setIncreaseCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                //待提交审核品牌
                operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(memberId);
                operateNoticeVO.setRoleId(memberRoleId);
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_VALIFY_COMMIT.getCode());
                operateNoticeVO.setIncreaseCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultBrandId;
    }

    /**
     * 删除品牌
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public String deleteBrand(UserLoginCacheDTO sysUser, Long id) {
        //验证数据库中是否存在该数据
        Brand brand = brandRepository.findById(id).orElse(null);
        if (brand != null) {
            Brand sourceBrand = brand.getSourceBrand();
            if (sourceBrand == null) {
                Boolean flag = goodsRepository.existsByBrandId(id);
                if (flag) {
                    throw new BusinessException(ResponseCode.PRODUCT_GOODS_RELATION_NOT_DELETE);
                }
                flag = commodityRepository.existsByBrandId(id);
                if (flag) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_RELATION_NOT_DELETE);
                }
            }
            brandRepository.deleteById(id);
            brandCheckRecordRepository.deleteByBrandId(id);

            try {
                List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                //品牌总数
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(brand.getMemberId());
                operateNoticeVO.setRoleId(brand.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.BRAND_COUNT.getCode());
                operateNoticeVO.setReduceCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                //待提交审核品牌
                operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(brand.getMemberId());
                operateNoticeVO.setRoleId(brand.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_VALIFY_COMMIT.getCode());
                operateNoticeVO.setReduceCount(1L);
                operateNoticeVOList.add(operateNoticeVO);
                reportControllerFeign.addOperateNoticeList(operateNoticeVOList);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResponseCode.SUCCESS.getMessage();
        }
        throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
    }

    /**
     * 启用/停用
     *
     * @param id
     * @param isEnable
     * @return
     */
    @Override
    public String updateBrandEnable(UserLoginCacheDTO sysUser, Long id, Boolean isEnable) {
        //验证数据库中是否存在该数据
        Brand brand = brandRepository.findById(id).orElse(null);
        if (brand != null) {
            if (!isEnable) {
                //审核通过状态才能停用
                Integer brandStatus = brand.getStatus();
                if (!CommodityStatusEnum.Pass.getCode().equals(brandStatus)) {
                    throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_PASS);
                }
                //判断会员属性是否有关联
                List<Commodity> commodityList = commodityRepository.findByBrandId(id);
                if (!commodityList.isEmpty()) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_RELATION_NOT_STOP);
                }
            }
            //持久化数据
            brand.setIsEnable(isEnable);
            brandRepository.saveAndFlush(brand);
            return ResponseCode.SUCCESS.getMessage();
        }
        throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
    }

    /**
     * 提交审核
     *
     * @param id 品牌id
     * @return 操作结果
     */
    @Transactional
    @Override
    public String applyCheckBrand(UserLoginCacheDTO sysUser, Long id) {
        //验证数据库中是否存在该数据
        Brand brand = brandRepository.findById(id).orElse(null);
        if (brand != null) {
            Integer current_status = brand.getStatus();
            if (!CommodityStatusEnum.Not_Submitted.getCode().equals(current_status)) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_STATUS_UNLEGAL);
            }
            Long time = System.currentTimeMillis();
            Integer new_status = CommodityStatusEnum.Not_Check.getCode();
            //持久化数据
            brand.setApplyTime(time);
            brand.setStatus(new_status);
            brandRepository.saveAndFlush(brand);

            BrandCheckRecord brandCheckRecord = new BrandCheckRecord();
            brandCheckRecord.setMemberRoleId(sysUser.getMemberRoleId());
            brandCheckRecord.setMemberRoleName(sysUser.getMemberRoleName());
            brandCheckRecord.setOperation(OperationEnum.Insert.getCode());
            brandCheckRecord.setStatus(new_status);
            brandCheckRecord.setCreateTime(time);
            brandCheckRecord.setBrandId(brand.getId());
            brandCheckRecordRepository.saveAndFlush(brandCheckRecord);

            //首页数据统计
            try {
                //会员待提交审核-1
                List<OperateNoticeVO> operateNoticeVOList = new ArrayList<>();
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(brand.getMemberId());
                operateNoticeVO.setRoleId(brand.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_VALIFY_COMMIT.getCode());
                operateNoticeVO.setReduceCount(1L);
                operateNoticeVOList.add(operateNoticeVO);

                operateNoticeVO = new OperateNoticeVO();
                if (CheckTypeEnum.MEMBER_CHECK.getCode().equals(brand.getType())) {
                    //能力中心待审核+1
                    operateNoticeVO.setMemberId(brand.getMemberId());
                    operateNoticeVO.setRoleId(brand.getMemberRoleId());
                } else {
                    //平台后台待审核+1
                    operateNoticeVO.setMemberId(0L);
                    operateNoticeVO.setRoleId(0L);
                }
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setIncreaseOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_CHECK_COMMIT.getCode());
                operateNoticeVO.setIncreaseCount(1L);
                operateNoticeVOList.add(operateNoticeVO);

                reportControllerFeign.addOperateNoticeList(operateNoticeVOList);

                //发送消息
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                if (CheckTypeEnum.MEMBER_CHECK.getCode().equals(brand.getType())) {
                    systemMessageRequest.setMemberId(0L);
                    systemMessageRequest.setRoleId(0L);
                } else {
                    systemMessageRequest.setMemberId(brand.getMemberId());
                    systemMessageRequest.setRoleId(brand.getMemberRoleId());
                }
                systemMessageRequest.setMessageNotice(MessageTemplateCode.brand_apply);
                List<String> params = new ArrayList<>();
                params.add(brand.getMemberName());
                systemMessageRequest.setParams(params);
                systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResponseCode.SUCCESS.getMessage();
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
        }
    }

    /**
     * 查询品牌审核记录
     *
     * @return List<BrandCheckRecord>
     */
    @Override
    public List<BrandCheckRecord> getBrandCheckRecord(Long brandId) {
        return brandCheckRecordRepository.findByBrandIdOrderByCreateTime(brandId);
    }

    /**
     * 查询品牌下拉框
     *
     * @param name 品牌名称
     * @return
     */
    @Override
    public List<SelectVO> getSelectBrand(Long memberId, Long memberRoleId, String name) {
        //根据条件查询
        Pageable pageable = PageRequest.of(0, Constants.SELECT_COUNT);
        Page<Brand> page;
        if (StringUtils.isNotEmpty(name)) {
            page = brandRepository.findByMemberIdAndMemberRoleIdAndNameContainingAndStatusAndIsEnableOrderByApplyTimeDesc(memberId, memberRoleId, name, CommodityStatusEnum.Pass.getCode(), true, pageable);
        } else {
            page = brandRepository.findByMemberIdAndMemberRoleIdAndStatusAndIsEnableOrderByApplyTimeDesc(memberId, memberRoleId, CommodityStatusEnum.Pass.getCode(), true, pageable);
        }
        //转换SelectVO实体
        return page.getContent().stream().map(brand -> {
            SelectVO selectVO = new SelectVO();
            selectVO.setId(brand.getId());
            selectVO.setName(brand.getName());
            return selectVO;
        }).collect(Collectors.toList());
    }

    /******************************************* 平台后台 *****************************************************/

    /**
     * 查询品牌下拉框 -- 平台后台
     *
     * @return
     */
    @Override
    public List<SelectVO> getSelectPlatformBrand(String name) {
        //根据条件查询
        Pageable pageable = PageRequest.of(0, Constants.SELECT_COUNT);
        Page<Brand> page;
        if (StringUtils.isNotEmpty(name)) {
            page = brandRepository.findByNameContainingAndStatusAndIsEnableOrderByApplyTimeDesc(name, CommodityStatusEnum.Pass.getCode(), true, pageable);
        } else {
            page = brandRepository.findByStatusAndIsEnableOrderByApplyTimeDesc(CommodityStatusEnum.Pass.getCode(), true, pageable);
        }
        //转换SelectVO实体
        return page.getContent().stream().map(brand -> {
            SelectVO selectVO = new SelectVO();
            selectVO.setId(brand.getId());
            selectVO.setName(brand.getName());
            return selectVO;
        }).collect(Collectors.toList());
    }

    /**
     * 查询品牌列表 -- 平台后台
     *
     * @param pageVO
     * @param name
     * @param status
     * @return Page<Attribute>
     */
    @Override
    public Page<Brand> getPlatformBrandList(PageVO pageVO, String name, Integer status) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        if (status != null && status > 0) {
            return brandRepository.findByNameContainingAndStatusOrderByApplyTimeDesc(name, status, page);
        } else {
            Integer not_status = CommodityStatusEnum.Not_Submitted.getCode();
            return brandRepository.findByNameContainingAndAndStatusNotOrderByApplyTimeDesc(name, not_status, page);
        }
    }

    /**
     * 查询待审核品牌列表--平台后台
     *
     * @param pageVO 分页实体
     * @param status 品牌状态(0-代表查全部,2-待审核,3-审核不通过,4-审核通过)
     * @return 列表
     */
    @Override
    public Page<Brand> getPlatformUnCheckBrandList(PageVO pageVO, Integer status) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return brandRepository.findByStatusAndTypeOrderByApplyTimeDesc(status, CheckTypeEnum.PLATFORM_CHECK.getCode(), page);
    }

    /**
     * 查询品牌 -- 平台后台
     *
     * @param id
     * @return Brand
     */
    @Override
    public Brand getBrand(Long id) {
        return brandRepository.findById(id).orElse(null);
    }

    /**
     * 审核-平台后台
     *
     * @param checkRequest
     * @return
     */
    @Transactional
    @Override
    public Long checkPlatformBrand(UserLoginCacheDTO sysUser, CheckRequest checkRequest) {
        Long resultBrandId;
        Long id = checkRequest.getId();
        Integer status = checkRequest.getStatus();
        String checkRemark = checkRequest.getCheckRemark();
        //先判断是否是成功或者不通过状态
        if (!CommodityStatusEnum.Not_Pass.getCode().equals(status) && !CommodityStatusEnum.Pass.getCode().equals(status)) {
            throw new BusinessException(ResponseCode.PRODUCT_BRAND_STATUS_UNLEGAL);
        }
        //验证数据库中是否存在该数据
        Brand brand = brandRepository.findById(id).orElse(null);
        if (brand != null) {
            Integer current_status = brand.getStatus();
            if (!CommodityStatusEnum.Not_Check.getCode().equals(current_status)) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_STATUS_UNLEGAL);
            }
            Long time = System.currentTimeMillis();

            //持久化数据
            brand.setCheckTime(time);
            brand.setStatus(status);
            Brand sourceBrand = brand.getSourceBrand();
            if (sourceBrand != null && CommodityStatusEnum.Pass.getCode().equals(status)) {
                String sourceBrandName = sourceBrand.getSourceBrandName();
                CopyOptions copyOptions = new CopyOptions();
                copyOptions.setIgnoreProperties("id");
                BeanUtil.copyProperties(brand, sourceBrand, copyOptions);
                //把副本的审核记录换成原品牌的审核记录
                List<BrandCheckRecord> brandCheckRecordList = brandCheckRecordRepository.findByBrandId(brand.getId());
                if (brandCheckRecordList != null && !brandCheckRecordList.isEmpty()) {
                    List<BrandCheckRecord> collect = brandCheckRecordList.stream().peek(brandCheckRecord -> brandCheckRecord.setBrandId(sourceBrand.getId())).collect(Collectors.toList());
                    brandCheckRecordRepository.saveAll(collect);
                }
                sourceBrand.setSourceBrandName(sourceBrandName);
                //删除副本，更新品牌信息
                brandRepository.delete(brand);
                brandRepository.saveAndFlush(sourceBrand);
                resultBrandId = sourceBrand.getId();
                //更新ES中品牌信息
                SimpleBrandResponse brandResponse = new SimpleBrandResponse();
                brandResponse.setId(sourceBrand.getId());
                brandResponse.setName(sourceBrand.getName());
                brandResponse.setLogoUrl(sourceBrand.getLogoUrl());
                syncEsCommodityService.updateCommodityBrand(brandResponse);
            } else {
                brandRepository.saveAndFlush(brand);
                resultBrandId = brand.getId();
            }

            BrandCheckRecord brandCheckRecord = new BrandCheckRecord();
            brandCheckRecord.setMemberRoleId(sysUser.getMemberRoleId());
            brandCheckRecord.setMemberRoleName(sysUser.getMemberRoleName());
            brandCheckRecord.setOperation(OperationEnum.Check.getCode());
            brandCheckRecord.setStatus(status);
            brandCheckRecord.setCheckRemark(checkRemark);
            brandCheckRecord.setCreateTime(time);
            brandCheckRecord.setBrandId(resultBrandId);
            brandCheckRecordRepository.saveAndFlush(brandCheckRecord);

            try {
                //平台后台待审核-1
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(0L);
                operateNoticeVO.setRoleId(0L);
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_CHECK_COMMIT.getCode());
                operateNoticeVO.setReduceCount(1L);
                reportControllerFeign.addOperateNotice(operateNoticeVO);

                //发送消息
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(brand.getMemberId());
                systemMessageRequest.setRoleId(brand.getMemberRoleId());
                systemMessageRequest.setMessageNotice(MessageTemplateCode.brand_audit);
                if (CommodityStatusEnum.Pass.getCode().equals(status)) {
                    systemMessageRequest.setParams(Arrays.asList(brand.getName(), CheckStatusEnum.AGREE.getMessage()));
                } else {
                    systemMessageRequest.setParams(Arrays.asList(brand.getName(), CheckStatusEnum.REFUSE.getMessage()));
                }
                systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return resultBrandId;
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
        }
    }

    /**
     * 审核-商品能力
     *
     * @param sysUser      当前登录用户
     * @param checkRequest 审核实体
     * @return 操作结果
     */
    @Override
    public Long checkBrand(UserLoginCacheDTO sysUser, CheckRequest checkRequest) {
        Long resultBrandId;
        Long id = checkRequest.getId();
        Integer status = checkRequest.getStatus();
        String checkRemark = checkRequest.getCheckRemark();
        //先判断是否是成功或者不通过状态
        if (!CommodityStatusEnum.Not_Pass.getCode().equals(status) && !CommodityStatusEnum.Pass.getCode().equals(status)) {
            throw new BusinessException(ResponseCode.PRODUCT_BRAND_STATUS_UNLEGAL);
        }
        //验证数据库中是否存在该数据
        Brand brand = brandRepository.findById(id).orElse(null);
        if (brand != null) {
            Integer current_status = brand.getStatus();
            if (!CommodityStatusEnum.Not_Check.getCode().equals(current_status)) {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_STATUS_UNLEGAL);
            }
            Long time = System.currentTimeMillis();

            //持久化数据
            brand.setCheckTime(time);
            brand.setStatus(status);
            Brand sourceBrand = brand.getSourceBrand();
            if (sourceBrand != null && CommodityStatusEnum.Pass.getCode().equals(status)) {
                String sourceBrandName = sourceBrand.getSourceBrandName();
                CopyOptions copyOptions = new CopyOptions();
                copyOptions.setIgnoreProperties("id");
                BeanUtil.copyProperties(brand, sourceBrand, copyOptions);
                //把副本的审核记录换成原品牌的审核记录
                List<BrandCheckRecord> brandCheckRecordList = brandCheckRecordRepository.findByBrandId(brand.getId());
                if (brandCheckRecordList != null && !brandCheckRecordList.isEmpty()) {
                    List<BrandCheckRecord> collect = brandCheckRecordList.stream().peek(brandCheckRecord -> brandCheckRecord.setBrandId(sourceBrand.getId())).collect(Collectors.toList());
                    brandCheckRecordRepository.saveAll(collect);
                }
                sourceBrand.setSourceBrandName(sourceBrandName);
                //删除副本，更新品牌信息
                brandRepository.delete(brand);
                brandRepository.saveAndFlush(sourceBrand);
                resultBrandId = sourceBrand.getId();
                //更新ES中品牌信息
                SimpleBrandResponse brandResponse = new SimpleBrandResponse();
                brandResponse.setId(sourceBrand.getId());
                brandResponse.setName(sourceBrand.getName());
                brandResponse.setLogoUrl(sourceBrand.getLogoUrl());
                syncEsCommodityService.updateCommodityBrand(brandResponse);
            } else {
                brandRepository.saveAndFlush(brand);
                resultBrandId = brand.getId();
            }

            BrandCheckRecord brandCheckRecord = new BrandCheckRecord();
            brandCheckRecord.setMemberRoleId(sysUser.getMemberRoleId());
            brandCheckRecord.setMemberRoleName(sysUser.getMemberRoleName());
            brandCheckRecord.setOperation(OperationEnum.Check.getCode());
            brandCheckRecord.setStatus(status);
            brandCheckRecord.setCheckRemark(checkRemark);
            brandCheckRecord.setCreateTime(time);
            brandCheckRecord.setBrandId(resultBrandId);
            brandCheckRecordRepository.saveAndFlush(brandCheckRecord);

            try {
                //商品能力待审核-1
                OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
                operateNoticeVO.setMemberId(brand.getMemberId());
                operateNoticeVO.setRoleId(brand.getMemberRoleId());
                operateNoticeVO.setDataSource(OperateDataSourceEnum.COMMODITY.getCode());
                operateNoticeVO.setReduceOperateType(CommodityOperateTypeEnum.TO_BE_BRAND_CHECK_COMMIT.getCode());
                operateNoticeVO.setReduceCount(1L);
                reportControllerFeign.addOperateNotice(operateNoticeVO);

                //发送消息
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(brand.getMemberId());
                systemMessageRequest.setRoleId(brand.getMemberRoleId());
                systemMessageRequest.setMessageNotice(MessageTemplateCode.brand_audit);
                if (CommodityStatusEnum.Pass.getCode().equals(status)) {
                    systemMessageRequest.setParams(Arrays.asList(brand.getName(), CheckStatusEnum.AGREE.getMessage()));
                } else {
                    systemMessageRequest.setParams(Arrays.asList(brand.getName(), CheckStatusEnum.REFUSE.getMessage()));
                }
                systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return resultBrandId;
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
        }
    }

    /**
     * 通过id查询品牌
     *
     * @param idList
     * @return
     */
    @Override
    public List<Brand> getBrandByIdList(List<Long> idList) {
        return brandRepository.findAllById(idList);
    }

    /**
     * 初始化数据到redis
     */
    @Async
    @Override
    public void initToRedis() {
        redisStringUtils.del(Constants.REDIS_KEY_BRAND, Constants.REDIS_PRODUCT_INDEX);
        List<Brand> brandList = brandRepository.findByStatusAndIsEnable(BrandStatusEnum.Pass.getCode(), true);
        if (!brandList.isEmpty()) {
            Map<String, String> map = new HashMap<>();
            brandList.forEach(brand -> map.put(String.valueOf(brand.getId()), JSONUtil.toJsonStr(brand)));
            redisStringUtils.hMSet(Constants.REDIS_KEY_BRAND, map, Constants.REDIS_PRODUCT_INDEX);
        }
    }

    /**
     * 根据会员属性获取品牌
     *
     * @param customerCategoryId
     * @return
     */
    @Override
    public List<BrandResponse> getBrandListByCustomerCategoryId(Long customerCategoryId) {
        List<Commodity> commodityList = commodityRepository.findAllByCustomerCategoryIdIn(new ArrayList<Long>(){{add(customerCategoryId);}});
        return getBrandResponse(commodityList);
    }

    private List<BrandResponse> getBrandResponse(List<Commodity> commodityList) {
        return commodityList.stream()
                .map(Commodity::getBrand)
                .filter(Objects::nonNull)
                .collect(Collectors
                        .collectingAndThen(
                                Collectors.toCollection(() ->
                                        new TreeSet<>(Comparator.comparing(Brand::getId))), ArrayList::new))
                .stream()
                .map(brand -> {
                    BrandResponse brandResponse = new BrandResponse();
                    BeanUtil.copyProperties(brand, brandResponse);
                    return brandResponse;
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据平台属性获取品牌
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<BrandResponse> getBrandListByCategoryId(Long categoryId) {
        List<Commodity> commodityList = commodityService.findAllByCategoryIdIn(new ArrayList<Long>(){{add(categoryId);}});
        return getBrandResponse(commodityList);
    }

}

